
from django.db import models
from user_app.models import User
from order_app.models import Order


class Notification(models.Model):
    """通知模型"""
    
    # 通知类型选项
    class Type(models.TextChoices):
        ORDER = 'order', '订单通知'
        PAYMENT = 'payment', '支付通知'
        SYSTEM = 'system', '系统通知'
        MESSAGE = 'message', '消息通知'
    
    # 通知级别选项
    class Level(models.TextChoices):
        INFO = 'info', '信息'
        SUCCESS = 'success', '成功'
        WARNING = 'warning', '警告'
        ERROR = 'error', '错误'
    
    # 基本信息
    recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='notifications', verbose_name='接收者')
    title = models.CharField(max_length=100, verbose_name='标题')
    content = models.TextField(verbose_name='内容')
    
    # 通知属性
    notification_type = models.CharField(max_length=20, choices=Type.choices, verbose_name='通知类型')
    level = models.CharField(max_length=20, choices=Level.choices, default=Level.INFO, verbose_name='通知级别')
    
    # 关联信息
    related_order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True, related_name='notifications', verbose_name='关联订单')
    
    # 状态信息
    is_read = models.BooleanField(default=False, verbose_name='是否已读')
    read_at = models.DateTimeField(null=True, blank=True, verbose_name='阅读时间')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '通知'
        verbose_name_plural = '通知'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['recipient', 'is_read', 'created_at']),
        ]
    
    def __str__(self):
        return f"{self.recipient.phone} 的通知: {self.title}"


class NotificationTemplate(models.Model):
    """通知模板模型"""
    
    # 模板代码，用于标识不同的通知场景
    code = models.CharField(max_length=50, unique=True, verbose_name='模板代码')
    title_template = models.CharField(max_length=100, verbose_name='标题模板')
    content_template = models.TextField(verbose_name='内容模板')
    
    # 通知属性
    notification_type = models.CharField(max_length=20, choices=Notification.Type.choices, verbose_name='通知类型')
    level = models.CharField(max_length=20, choices=Notification.Level.choices, default=Notification.Level.INFO, verbose_name='通知级别')
    
    # 微信模板消息ID
    wechat_template_id = models.CharField(max_length=64, null=True, blank=True, verbose_name='微信模板ID')
    
    # 是否启用
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    
    # 备注
    remark = models.TextField(null=True, blank=True, verbose_name='备注')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '通知模板'
        verbose_name_plural = '通知模板'
    
    def __str__(self):
        return f"通知模板: {self.code}"


class WechatSubscription(models.Model):
    """微信订阅消息模型"""
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='wechat_subscriptions', verbose_name='用户')
    template_id = models.CharField(max_length=64, verbose_name='模板ID')
    subscription_id = models.CharField(max_length=64, verbose_name='订阅ID')
    
    # 订阅状态
    is_active = models.BooleanField(default=True, verbose_name='是否有效')
    
    # 过期时间
    expires_at = models.DateTimeField(verbose_name='过期时间')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '微信订阅消息'
        verbose_name_plural = '微信订阅消息'
        unique_together = ['user', 'template_id']
    
    def __str__(self):
        return f"{self.user.phone} 订阅的模板 {self.template_id}"


class MessageRecord(models.Model):
    """消息发送记录模型"""
    
    # 消息类型选项
    class Type(models.TextChoices):
        WECHAT = 'wechat', '微信模板消息'
        SMS = 'sms', '短信'
        APP = 'app', '应用内推送'
        EMAIL = 'email', '邮件'
    
    # 发送状态选项
    class Status(models.TextChoices):
        PENDING = 'pending', '待发送'
        SENT = 'sent', '已发送'
        DELIVERED = 'delivered', '已送达'
        FAILED = 'failed', '发送失败'
    
    notification = models.ForeignKey(Notification, on_delete=models.CASCADE, related_name='message_records', verbose_name='通知')
    message_type = models.CharField(max_length=20, choices=Type.choices, verbose_name='消息类型')
    recipient_id = models.CharField(max_length=64, verbose_name='接收者ID')  # 可能是openid、手机号等
    
    # 消息内容
    title = models.CharField(max_length=100, verbose_name='标题')
    content = models.TextField(verbose_name='内容')
    template_data = models.JSONField(null=True, blank=True, verbose_name='模板数据')
    
    # 发送状态
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING, verbose_name='发送状态')
    error_message = models.TextField(null=True, blank=True, verbose_name='错误信息')
    
    # 第三方消息ID
    external_id = models.CharField(max_length=64, null=True, blank=True, verbose_name='外部消息ID')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    sent_at = models.DateTimeField(null=True, blank=True, verbose_name='发送时间')
    delivered_at = models.DateTimeField(null=True, blank=True, verbose_name='送达时间')
    
    class Meta:
        verbose_name = '消息发送记录'
        verbose_name_plural = '消息发送记录'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.get_message_type_display()} 消息 - {self.status}"